﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace ALinq.BBS.DataAccess
{
    public class Forums : IEnumerable<Forum>
    {
        private readonly Board board;
        private List<Forum> items;

        internal Forums(Board board)
        {
            this.board = board;
        }

        private IList<Forum> Items
        {
            get
            {
                if (items == null)
                    items = board.DataContext.Forums.Where(o => o.BoardID == board.ID).ToList();

                return items;
            }
        }

        public IEnumerator<Forum> GetEnumerator()
        {
            return Items.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public Forum AddItem(string name)
        {
            var list = Items;
            var forum = new Forum();
            forum.ID = board.DataContext.Forums.Max(o => o.ID) + 1;
            forum.Name = name;
            forum.BoardID = board.ID;

            board.DataContext.Forums.Insert(forum);
            list.Add(forum);

            return forum;
        }

        public int Count
        {
            get { return Items.Count; }
        }

        public void DeleteItems(IEnumerable<int> ids)
        {
            board.DataContext.Forums.Delete(o => ids.Contains(o.ID));
            var q = Items.Where(o => ids.Contains(o.ID)).ToList();
            q.ForEach(o => Items.Remove(o));
        }

        public void DeleteItem(int deleteItemID)
        {
            DeleteItems(new[] { deleteItemID });
        }

        public void UpdateItem(int id, string name)
        {
            board.DataContext.Forums.Update(o => new Forum { Name = name }, 
                                            o => o.ID == id);
        }


    }
}